package com.oodso.sell.model.util;

import android.text.TextUtils;

import com.oodso.sell.SellApplication;
import com.oodso.sell.model.StringHttp;
import com.oodso.sell.utils.SignoutUtils;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * 项目名称：Sosoliuda
 * 类描述：请求拦截器
 * 创建人：周作威
 * 创建时间：2016/12/13
 */

public class MouseInterceptor implements Interceptor {
    private TreeMap<String, String> mPublicParams = new TreeMap<>();
    private String appkey;
    private String sercet;


    public MouseInterceptor() {
        // 1.设置公共参数
        mPublicParams.put("format", "json");
        mPublicParams.put("v", "1.0");
    }


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        request = getRequest(request);
        return chain.proceed(request);
    }


    private Request getRequest(Request request) {
        Request.Builder builder = request.newBuilder();
        TreeMap params = new TreeMap<>(mPublicParams);
//        String host = request.url().host();


//         appkey = TextUtils.isEmpty(HttpConstans.APP_KEY)?HttpConstans.APP_KEY_DUOSHU:HttpConstans.APP_KEY;
//         sercet = TextUtils.isEmpty(HttpConstans.APP_SERCET)?HttpConstans.APP_SERCET_DUOSHU:HttpConstans.APP_SERCET;
        String appkey = SignoutUtils.getInstance().getAppkey();
        String sercet = SignoutUtils.getInstance().getAppsercet();
        params.put("app_key", appkey);

        if (TextUtils.isEmpty(SellApplication.getInstance().getToken())) {
            params.put("session", null);
        } else {
            params.put("session", SellApplication.getInstance().getToken());
        }

        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        // 排序加密
        if (canInjectIntoBody(request)) {
            String postBodyString = bodyToString(request.body());
            Map<String, String> urlParams = UrlUtil
                    .convertParamsString2Map(postBodyString);
            params.putAll(urlParams);
            params.put("sign", StringHttp.signRequest(params, sercet));

            RequestBody body = RequestBody.create(MediaType
                    .parse("application/x-www-form-urlencoded;charset=UTF-8"), UrlUtil
                    .convertParamsMap2String(params, false));
            builder.post(body);
        } else {
            // can't inject into body, then inject into url
            injectParamsIntoUrl(request, builder, params, sercet);
        }

        request = builder.build();
        return request;
    }


    private boolean canInjectIntoBody(Request request) {
        if (request == null) {
            return false;
        }
        if (!TextUtils.equals(request.method(), "POST")) {
            return false;
        }
        RequestBody body = request.body();
        if (body == null) {
            return false;
        }
        return true;
        //MediaType mediaType = body.contentType();
        //return mediaType != null &&
        //        TextUtils.equals(mediaType.subtype(), "x-www-form-urlencoded");
    }


    // func to inject params into url
    private void injectParamsIntoUrl(Request request, Request.Builder requestBuilder, TreeMap<String, String> params, String sercet) {
        HttpUrl.Builder httpUrlBuilder = request.url().newBuilder();
        httpUrlBuilder.addQueryParameter("app_key", params.get("app_key"));
        httpUrlBuilder.addQueryParameter("format", params.get("format"));
        httpUrlBuilder.addQueryParameter("v", params.get("v"));
        httpUrlBuilder.addQueryParameter("session", params.get("session"));
        httpUrlBuilder.addQueryParameter("timestamp", params.get("timestamp"));
        String query = httpUrlBuilder.build().url().getQuery();
        Map<String, String> map = UrlUtil.convertParamsString2Map(query);
        params.putAll(map);
        httpUrlBuilder.addQueryParameter("sign", StringHttp
                .signRequest(params, sercet));
        requestBuilder.url(httpUrlBuilder.build());
    }


    private static String bodyToString(final RequestBody request) {
        try {
            final Buffer buffer = new Buffer();
            if (request != null) {
                request.writeTo(buffer);
            } else {
                return "";
            }
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}
